import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { authService } from '../services/auth';

// 定义用户接口
interface User {
  id: number;
  email: string;
  firstName?: string;
  lastName?: string;
  picture?: string;
  provider: 'local' | 'google' | 'github';
}

// 定义认证上下文接口
interface AuthContextType {
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  login: (email: string, password: string) => Promise<void>;
  register: (userData: {
    firstName?: string;
    lastName?: string;
    email: string;
    password: string;
  }) => Promise<void>;
  loginWithGoogle: (code: string) => Promise<void>;
  loginWithGithub: (code: string) => Promise<void>;
  logout: () => Promise<void>;
  refreshUserInfo: () => Promise<void>;
  updateUser: (user: User) => void;
}

// 创建上下文
const AuthContext = createContext<AuthContextType | undefined>(undefined);

// Provider组件的props接口
interface AuthProviderProps {
  children: ReactNode;
}

// AuthProvider组件
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // 初始化时检查用户登录状态
  useEffect(() => {
    const initializeAuth = async () => {
      try {
        setIsLoading(true);
        
        // 检查本地存储中是否有用户信息
        const storedUser = authService.getStoredUser();
        if (storedUser && authService.isAuthenticated()) {
          // 验证token是否仍然有效
          const isValid = await authService.validateToken();
          if (isValid) {
            setUser(storedUser);
          } else {
            // Token无效，清除本地数据
            await authService.logout();
            setUser(null);
          }
        }
      } catch (error) {
        console.error('初始化认证状态失败:', error);
        await authService.logout();
        setUser(null);
      } finally {
        setIsLoading(false);
      }
    };

    initializeAuth();
  }, []);

  // 注册方法
  const register = async (userData: {
    firstName?: string;
    lastName?: string;
    email: string;
    password: string;
  }): Promise<void> => {
    try {
      setIsLoading(true);
      const response = await authService.register(userData);
      setUser(response.data.user);
    } catch (error) {
      throw error;
    } finally {
      setIsLoading(false);
    }
  };

  // 登录方法
  const login = async (email: string, password: string): Promise<void> => {
    try {
      setIsLoading(true);
      const response = await authService.login(email, password);
      setUser(response.data.user);
    } catch (error) {
      throw error;
    } finally {
      setIsLoading(false);
    }
  };

  // Google登录方法
  const loginWithGoogle = async (code: string): Promise<void> => {
    try {
      setIsLoading(true);
      const response = await authService.loginWithGoogle(code);
      setUser(response.data.user);
    } catch (error) {
      throw error;
    } finally {
      setIsLoading(false);
    }
  };

  // GitHub登录方法
  const loginWithGithub = async (code: string): Promise<void> => {
    try {
      setIsLoading(true);
      const response = await authService.loginWithGithub(code);
      setUser(response.data.user);
    } catch (error) {
      throw error;
    } finally {
      setIsLoading(false);
    }
  };

  // 登出方法
  const logout = async (): Promise<void> => {
    try {
      setIsLoading(true);
      await authService.logout();
      setUser(null);
    } catch (error) {
      console.error('登出失败:', error);
      // 即使后端登出失败，也要清除本地状态
      setUser(null);
    } finally {
      setIsLoading(false);
    }
  };

  // 刷新用户信息
  const refreshUserInfo = async (): Promise<void> => {
    try {
      if (authService.isAuthenticated()) {
        const userInfo = await authService.getCurrentUser();
        setUser(userInfo);
      }
    } catch (error) {
      console.error('刷新用户信息失败:', error);
    }
  };

  // 更新用户信息
  const updateUser = (updatedUser: User): void => {
    setUser(updatedUser);
    // 可能需要更新本地存储
    authService.updateStoredUser(updatedUser);
  };

  // 上下文值
  const value: AuthContextType = {
    user,
    isAuthenticated: !!user,
    isLoading,
    login,
    register,
    loginWithGoogle,
    loginWithGithub,
    logout,
    refreshUserInfo,
    updateUser,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};

// 自定义Hook来使用认证上下文
export const useAuth = (): AuthContextType => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

// 导出上下文供高级用法使用
export { AuthContext };